package reflect;

import reflect.annotation.AutoRunClass;
import reflect.annotation.AutoRunMethod;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URISyntaxException;

public class Test8 {
    public static void main(String[] args) throws URISyntaxException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException {
        File dir = new File(
                Test8.class.getResource(".").toURI()
        );
        String packName = Test8.class.getPackage().getName();
        File[] files = dir.listFiles(f -> f.getName().endsWith(".class"));
        for (File sub : files) {
            String fileName = sub.getName();
            String className = fileName.substring(0, fileName.indexOf("."));
            Class cls = Class.forName(packName + "." + className);
            if (cls.isAnnotationPresent(AutoRunClass.class)) {
                System.out.println("实例化：" + className);
                Object obj = cls.newInstance();
                System.out.println(obj);
                Method[] methods = cls.getDeclaredMethods();
                for (Method method : methods) {
                    if (method.isAnnotationPresent(AutoRunMethod.class)) {
                        System.out.println("执行方法：" + method.getName() + "()...");
                        method.invoke(obj);
                    }
                }
            }
        }
    }
}
